from itertools import groupby
from operator import itemgetter

from flask import request
from sqlalchemy import and_, func

from apps.libs.redprint import Redprint
from apps.libs.token_auth import auth
from apps.models.base import db
from apps.models.course import Course
from apps.models.course_cate import CourseCate
from apps.models.lesson import Lesson
from apps.models.level import Level

from apps.libs.error_code import ParameterException, NotFound, Success
from apps.models.musics import Music

api = Redprint('course')

@api.route('/coursecate/', methods=['POST'])
@auth.login_required
def courseCate():
    level_id = request.json.get('level_id', 0)
    if not level_id:
        return ParameterException('缺少参数！')
    cate_list = CourseCate.query.filter_by(level_id=level_id).all()
    if not cate_list:
        return NotFound()
    resp = [{'cate_id': cate.id, 'name': cate.name} for cate in cate_list]
    return Success(data=resp)


@api.route('/courselist/', methods=['POST'])
@auth.login_required
def courseList():
    level_id = request.json.get('level_id', 0)
    cate_id = request.json.get('cate_id', 0)
    if not level_id or not cate_id:
        return ParameterException('缺少参数！')
    course_list = Course.query.filter_by(level_id=level_id, cate_id=cate_id).all()
    if not course_list:
        return NotFound()
    resp = [{'course_id': course.id, 'name': course.name} for course in course_list]
    return Success(data=resp)


@api.route('/musiclist/', methods=['POST'])
@auth.login_required
def musicList():
    cate_id = request.json.get('cate_id')
    if not cate_id:
        return ParameterException('缺少参数！')
    musiclist = Music.query.filter_by(cate_id=cate_id).all()
    resp = [{'title': music.title, 'url': music.url, 'id': music.id, 'from': music._from, 'lesson_n': music.lesson_n} for music in musiclist]
    return Success(data=resp)


@api.route('/lessonlist/', methods=['POST'])
@auth.login_required
def lessonList():
    cate_id = request.json.get('cate_id', 0)
    if not cate_id:
        return ParameterException('缺少参数！')
    query = db.session.query(Lesson.course_id).filter(Lesson.cate_id==cate_id)
    # lesson_list = db.session.query(Course, Lesson).join(Lesson, and_(Lesson.course_id==Course.id, Lesson.cate_id==cate_id)).all()
    course_ids = query.distinct().all()
    my_lessons = []
    for course_id, in course_ids:
        course = Course.query.filter_by(id=course_id).first()
        lessons = Lesson.query.filter(Lesson.course_id==course_id).all()
        my_course = {
            'course_id': course.id,
            'name': course.name,
            'lessons': [{'id': lesson.id, 'name': lesson.name, 'url': lesson.url, 'lesson_n': lesson.lesson_n, 'desc': lesson.desc} for lesson in lessons]
        }
        my_lessons.append(my_course)
    if not my_lessons:
        return NotFound()
    
    resp = my_lessons
    return Success(data=resp)